package portal.monitor.controller;


import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import beans.HttpResultList;
import net.sf.json.JSONObject;
import portal.monitor.dao.MonitorHost;
import portal.monitor.dao.MonitorHostGroup;
import portal.monitor.dao.MonitorHostGroupPage;
import portal.monitor.dao.MonitorRelated;
import portal.monitor.dao.service.MonitorHostGroupService;
import portal.monitor.dao.service.MonitorHostService;
import portal.monitor.dao.service.MonitorRelatedService;
import utils.Log4jInit;

@RestController
public class MonitorHostGroupServlet {
    @Autowired
    MonitorHostGroupService monitorHostGroupService;
    private HttpResultList result;
    @Autowired
    MonitorRelatedService monitorRelatedService;
    @Autowired
    MonitorHostService monitorHostService;
    

    @RequestMapping(value = "/MonitorHostGroupServlet", method = RequestMethod.POST)
    public void HostGroupService(HttpServletRequest request, HttpServletResponse response) throws IOException {
        result = new HttpResultList();
        String operateType = request.getParameter("operateType");
        try {
            switch (operateType) {
                case "add":
                    addHostGroup(request);
                    break;
                case "delete":
                    deleteHostGroup(request);
                    break;
                case "alter":
                    alterHostGroup(request);
                    break;
                case "showAll":
                    showAll();
                    break;
                case "showPaged":
                    showPaged(request);
                    break;
                case "showDetail":
                    showDetail(request);
                    break;
            }
        } catch (NullPointerException e) {
            e.printStackTrace();
            result.setResult(false);
            result.setMessage("POST参数错误");
            response.getWriter().print(JSONObject.fromObject(result).toString());
        } catch (NumberFormatException e) {
            e.printStackTrace();
            result.setResult(false);
            result.setMessage("POST数字错误");
        }
        response.getWriter().print(JSONObject.fromObject(result).toString());
    }

    private void addHostGroup(HttpServletRequest request) {
        String hostGroupName = request.getParameter("hostGroupName");
        String introduction = request.getParameter("introduction");
        String hostsId = request.getParameter("groupHostsId");
        MonitorHostGroup monitorHostGroup = new MonitorHostGroup(hostGroupName, introduction);
        boolean res = monitorHostGroupService.insert(monitorHostGroup) == 1;
        if(res){
        	MonitorHostGroup m = monitorHostGroupService.getNewsetRec();
        	String[] hostIds = hostsId.split(",");
        	for(String s:hostIds){
        		MonitorRelated monitorRelated = new MonitorRelated(Integer.parseInt(s),m.getHostGroupId());
        		monitorRelatedService.insert(monitorRelated);
        	}
        }
//        setHostGroupRelate(String.valueOf(hostGroupId),hostsId);
        result.setResult(res);
    }

    private void deleteHostGroup(HttpServletRequest request) {
        Integer hostGroupId = Integer.parseInt(request.getParameter("hostGroupId"));
        boolean res = monitorHostGroupService.deleteByPrimaryKey(hostGroupId) == 1;
    		monitorRelatedService.deleteByGroupId(hostGroupId);
        result.setResult(res);
    }

    private void alterHostGroup(HttpServletRequest request) {
        Integer hostGroupId = Integer.parseInt(request.getParameter("hostGroupId"));
        String hostGroupName = request.getParameter("hostGroupName");
        String introduction = request.getParameter("introduction");
        String hostsId = request.getParameter("groupHostsId");
        MonitorHostGroup monitorHostGroup = new MonitorHostGroup(hostGroupId, hostGroupName, introduction);
        boolean res = monitorHostGroupService.updateByPrimaryKey(monitorHostGroup) == 1;
        setHostGroupRelate(String.valueOf(hostGroupId),hostsId);
        result.setResult(res);
    }

    private void showAll() {
        List<MonitorHostGroup> hostGroupList = monitorHostGroupService.selectAll();
        List<Object> objects = new ArrayList<Object>(hostGroupList);
        result.setResult(objects.size() > 0);
        result.setDatas(objects);
    }

    private void showPaged(HttpServletRequest request) {
        Integer currentPage = Integer.parseInt(request.getParameter("currentPage"));
        Integer onePageCount = Integer.parseInt(request.getParameter("onePageCount"));
        List<MonitorHostGroup> hostGroupList = monitorHostGroupService.selectByPage(currentPage, onePageCount);
        List<MonitorHostGroupPage> hostGroupListPage = new ArrayList<MonitorHostGroupPage>();
        for(MonitorHostGroup m:hostGroupList){
        	MonitorHostGroupPage groupPage = new MonitorHostGroupPage(m);
        	List<MonitorRelated> monitorRelated = monitorRelatedService.selectByGroupId(m.getHostGroupId());
        
        	StringBuilder hosts = new StringBuilder();
        	for(MonitorRelated mr:monitorRelated){
        		MonitorHost host = monitorHostService.selectByPrimaryKey(mr.getHostId());
        		if(host!=null){
        			hosts.append(",");
        			hosts.append(host.getHostName());
//            		Log4jInit.logger.info("=====gourp hosts: "+hosts.toString());
        		}
        	}
        	if(monitorRelated.size()>0){
            	//	continue;
        		hosts.deleteCharAt(0);
        		groupPage.setHosts(hosts.toString());
            	}
        	hostGroupListPage.add(groupPage);
        }
        List<Object> objects = new ArrayList<Object>(hostGroupListPage);
        int pageNum = monitorHostGroupService.pageNum(onePageCount);
        result.setResult(objects.size() > 0);
        result.setMessage(pageNum + "");
        result.setDatas(objects);
    }

    private void showDetail(HttpServletRequest request) {
        Integer hostGroupId = Integer.parseInt(request.getParameter("hostGroupId"));
        MonitorHostGroup monitorHostGroup= monitorHostGroupService.selectByPrimaryKey(hostGroupId);
        List<Object> objects = new ArrayList<>();
        objects.add(monitorHostGroup);
        result.setResult(monitorHostGroup != null);
        result.setDatas(objects);
    }
    
    public void setHostGroupRelate(String groupId,String hostIds){
    	
    	monitorRelatedService.deleteByGroupId(Integer.valueOf(groupId));
    	String[] hosts = hostIds.split(",");
    	for(String s:hosts){
    		MonitorRelated mr = new MonitorRelated(Integer.valueOf(s),Integer.valueOf(groupId));
    		monitorRelatedService.insert(mr);
    	}
    	
    }
}
